package com.sym.architecture.view

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.sym.architecture.CalActivity
import com.sym.architecture.R
import com.sym.architecture.ext.alert
import com.sym.architecture.ext.run
import com.sym.architecture.ext.runDelay
import com.sym.architecture.network.SymCoroutineScope
import com.sym.architecture.network.SymCoroutineScope1
import com.sym.architecture.vm.MainVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"
    val mHandler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun showDialog(view: View) {

        lifecycleScope.launch {
            val ret = alert("标题", "Hello world")
            Log.i(TAG, "dialog 返回结果是 ：$ret")
        }
    }

    @ExperimentalCoroutinesApi
    fun handler(view: View) {

        lifecycleScope.launch {
            val ret = mHandler.run {
                "mHandle  run Hello world!"
            }
            Log.i(TAG, ret)

            val ret1 = mHandler.runDelay(1000L) {
                "mHandler runDelay Hello world"
            }

            String.format("%s", "hello world!");
            Log.i(TAG, ret1)
        }
    }

    fun coroutine(view: View) {
        SymCoroutineScope(Dispatchers.Default).launch {

            Log.i(TAG, "the name of current thread is  ${Thread.currentThread().name}")
        }

        SymCoroutineScope1.launch {
            Log.i(TAG, "the name of current thread is  ${Thread.currentThread().name}")
        }
    }

    fun dataStore(view: View) {
        /*val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
        baseContext.dataStore.data.map { preferences ->
            preferences[EXAMPLE_COUNTER] ?: 0
        }*/
    }

    fun cal(view: View) {
        /* val pak = AppUtils.getAllApps(this, "Calculator", "calculator")

         if (null != pak) {
             val intent = packageManager.getLaunchIntentForPackage(pak.packageName)
             startActivity(intent)
         }*/

        val intent = Intent(this, CalActivity::class.java)
        startActivity(intent)
    }

    fun flowRequest(view: View) {

        val vm = ViewModelProvider(this).get(MainVm::class.java)
        vm.requestFlowData()
    }
}